<template>
  <div class="event-page">
    <!-- 活动头部 -->
    <section class="event-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <el-breadcrumb>
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <template v-if="route.query.from === 'community'">
            <el-breadcrumb-item :to="{ path: '/community' }"
              >社区</el-breadcrumb-item
            >
            <el-breadcrumb-item
              :to="{ path: '/community', query: { tab: 'events' } }"
              >活动</el-breadcrumb-item
            >
          </template>
          <template v-else-if="route.query.from === 'events'">
            <el-breadcrumb-item :to="{ path: '/events' }"
              >活动日历</el-breadcrumb-item
            >
          </template>
          <el-breadcrumb-item>{{
            event.title || "活动详情"
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div class="container mx-auto px-4 py-8">
        <div class="max-w-4xl mx-auto">
          <!-- 活动标题 -->
          <h1 class="text-3xl font-bold mb-4">{{ event.title }}</h1>

          <!-- 活动状态和标签 -->
          <div class="flex items-center gap-4 mb-6">
            <el-tag
              :type="event.status === 'upcoming' ? 'warning' : 'success'"
              size="large"
            >
              {{ event.status === "upcoming" ? "即将开始" : "进行中" }}
            </el-tag>
            <el-tag type="info" size="large" v-if="event.fee === 0"
              >免费活动</el-tag
            >
            <el-tag type="danger" size="large" v-else>付费活动</el-tag>
            <span class="text-gray-500">
              报名截止：{{ formatDate(event.registrationEndTime) }}
            </span>
          </div>

          <!-- 活动封面 -->
          <div class="cover-image mb-8 rounded-lg overflow-hidden shadow-lg">
            <el-image
              :src="event.coverImage"
              fit="cover"
              class="w-full h-[400px] object-center hover:scale-105 transition-transform duration-300"
              :preview-src-list="[event.coverImage]"
            />
          </div>

          <!-- 活动信息卡片 -->
          <div
            class="info-card bg-gray-50 dark:bg-gray-700 rounded-lg p-6 mb-8"
          >
            <div class="grid grid-cols-2 gap-6">
              <div class="info-item">
                <div class="text-gray-500 mb-2">活动时间</div>
                <div class="flex items-center text-lg">
                  <el-icon class="mr-2"><Calendar /></el-icon>
                  {{ formatDate(event.startTime) }} -
                  {{ formatDate(event.endTime) }}
                </div>
              </div>
              <div class="info-item">
                <div class="text-gray-500 mb-2">活动地点</div>
                <div class="flex items-center text-lg">
                  <el-icon class="mr-2"><Location /></el-icon>
                  {{ event.location }}
                  <el-button
                    type="primary"
                    link
                    class="ml-2"
                    @click="showMap = true"
                  >
                    <el-icon><MapLocation /></el-icon>
                    查看地图
                  </el-button>
                </div>
              </div>
              <div class="info-item">
                <div class="text-gray-500 mb-2">活动费用</div>
                <div class="flex items-center text-lg">
                  <el-icon class="mr-2"><Ticket /></el-icon>
                  {{ event.fee === 0 ? "免费" : `¥${event.fee}` }}
                  <el-tooltip
                    v-if="event.fee > 0"
                    content="费用包含活动全程的餐饮和材料"
                    placement="top"
                  >
                    <el-icon class="ml-2"><InfoFilled /></el-icon>
                  </el-tooltip>
                </div>
              </div>
              <div class="info-item">
                <div class="text-gray-500 mb-2">报名人数</div>
                <div class="flex items-center text-lg">
                  <el-icon class="mr-2"><User /></el-icon>
                  <el-progress
                    :percentage="
                      Math.round(
                        (event.participantsCount / event.maxParticipants) * 100,
                      )
                    "
                    :format="
                      () =>
                        `${event.participantsCount}/${event.maxParticipants}`
                    "
                    class="flex-1"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons flex items-center justify-between mb-8">
            <div class="flex items-center gap-4">
              <el-button
                type="primary"
                size="large"
                :disabled="!canRegister"
                @click="handleRegister"
              >
                <el-icon><Ticket /></el-icon>
                {{ getRegisterButtonText() }}
              </el-button>
              <el-button size="large" @click="handleShare">
                <el-icon><Share /></el-icon>
                分享活动
              </el-button>
              <el-button size="large" @click="handleAddCalendar">
                <el-icon><Calendar /></el-icon>
                添加到日历
              </el-button>
            </div>
            <el-button
              :type="event.isFollowing ? 'success' : 'default'"
              size="large"
              @click="handleFollow"
            >
              <el-icon><Star /></el-icon>
              {{ event.isFollowing ? "已关注" : "关注活动" }}
            </el-button>
          </div>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex gap-8">
        <!-- 左侧内容 -->
        <div class="flex-1">
          <!-- 活动详情 -->
          <div
            class="content-card bg-white dark:bg-gray-800 rounded-lg p-8 mb-8"
          >
            <h2 class="text-xl font-bold mb-6 flex items-center">
              <el-icon class="mr-2"><Document /></el-icon>
              活动详情
            </h2>
            <div
              class="prose prose-lg dark:prose-invert max-w-none"
              v-html="event.content"
            ></div>
          </div>

          <!-- 活动须知 -->
          <div
            class="content-card bg-white dark:bg-gray-800 rounded-lg p-8 mb-8"
          >
            <h2 class="text-xl font-bold mb-6 flex items-center">
              <el-icon class="mr-2"><InfoFilled /></el-icon>
              活动须知
            </h2>
            <div class="space-y-4">
              <div
                v-for="(notice, index) in event.notices"
                :key="index"
                class="notice-item"
              >
                <h3 class="font-medium mb-2 flex items-center">
                  <el-icon class="mr-2"><Warning /></el-icon>
                  {{ notice.title }}
                </h3>
                <p class="text-gray-600 dark:text-gray-400 pl-6">
                  {{ notice.content }}
                </p>
              </div>
            </div>
          </div>

          <!-- 报名表单 -->
          <div
            v-if="showRegistrationForm"
            class="content-card bg-white dark:bg-gray-800 rounded-lg p-8"
          >
            <h2 class="text-xl font-bold mb-6 flex items-center">
              <el-icon class="mr-2"><Edit /></el-icon>
              报名信息
            </h2>
            <el-form
              ref="registrationForm"
              :model="formData"
              :rules="formRules"
              label-width="100px"
            >
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入真实姓名"
                />
              </el-form-item>
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号码"
                />
              </el-form-item>
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model="formData.idCard"
                  placeholder="请输入身份证号"
                />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息（选填）"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitRegistration">
                  提交报名
                </el-button>
                <el-button @click="showRegistrationForm = false"
                  >取消</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar w-80">
          <!-- 主办方信息 -->
          <div
            class="organizer-card bg-white dark:bg-gray-800 rounded-lg p-6 mb-6"
          >
            <h3 class="text-lg font-bold mb-4 flex items-center">
              <el-icon class="mr-2"><OfficeBuilding /></el-icon>
              主办方
            </h3>
            <div class="flex items-center">
              <el-avatar :size="48" :src="event.organizer.avatar" />
              <div class="ml-3">
                <div class="font-medium">{{ event.organizer.name }}</div>
                <div class="text-sm text-gray-500">
                  已举办 {{ event.organizer.eventsCount }} 场活动
                </div>
              </div>
            </div>
            <div class="mt-4 text-gray-600 dark:text-gray-400">
              {{ event.organizer.description }}
            </div>
            <el-button
              type="primary"
              link
              class="mt-4 w-full"
              @click="handleContactOrganizer"
            >
              联系主办方
            </el-button>
          </div>

          <!-- 参与者列表 -->
          <div
            class="participants-card bg-white dark:bg-gray-800 rounded-lg p-6"
          >
            <div class="flex items-center justify-between mb-4">
              <h3 class="text-lg font-bold flex items-center">
                <el-icon class="mr-2"><User /></el-icon>
                参与者
              </h3>
              <span class="text-gray-500">
                {{ event.participantsCount }}/{{ event.maxParticipants }}
              </span>
            </div>
            <div class="participants-list space-y-4">
              <div
                v-for="participant in event.participants"
                :key="participant.id"
                class="participant-item flex items-center"
              >
                <el-avatar :size="40" :src="participant.avatar" />
                <div class="ml-3">
                  <div class="font-medium">{{ participant.nickname }}</div>
                  <div class="text-sm text-gray-500">
                    {{ formatTime(participant.registerTime) }}报名
                  </div>
                </div>
              </div>
            </div>
            <el-button
              v-if="event.participants.length >= 5"
              type="primary"
              link
              class="mt-4 w-full"
            >
              查看更多参与者
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 地图弹窗 -->
    <el-dialog
      v-model="showMap"
      title="活动地点"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="h-[400px]">
        <!-- 这里可以集成地图组件 -->
        <div
          class="w-full h-full bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-center"
        >
          地图组件占位
        </div>
      </div>
    </el-dialog>

    <!-- 分享弹窗 -->
    <ShareDialog
      v-model="showShareDialog"
      :title="event.title"
      :url="generateShareUrl()"
      :platforms="sharePlatforms"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Calendar,
  Location,
  Ticket,
  User,
  Share,
  MapLocation,
  InfoFilled,
  Document,
  Warning,
  Edit,
  OfficeBuilding,
  Star,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import ShareDialog from "@/components/global/ShareDialog.vue";
import service from "@/api/axios";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const route = useRoute();
const router = useRouter();

// 活动信息
const event = ref({
  id: "",
  title: "",
  status: "",
  content: "",
  coverImage: "",
  startTime: "",
  endTime: "",
  registrationEndTime: "",
  location: "",
  fee: 0,
  maxParticipants: 0,
  participantsCount: 0,
  isRegistered: false,
  isFollowing: false,
  organizer: {
    name: "",
    avatar: "",
    description: "",
    eventsCount: 0,
  },
  notices: [],
  participants: [],
});

// 测试数据
const mockEventData = {
  id: route.params.id,
  title: "2024贵港文化节：非遗展演专场",
  status: "upcoming",
  content: `
    <h2>活动介绍</h2>
    <p>2024贵港文化节非遗展演专场将在贵港市文化中心隆重举行。本次活动将集中展示贵港地区非物质文化遗产，包括传统工艺、民间艺术、传统戏曲等多个领域的精彩表演和展示。</p>
    <h2>活动亮点</h2>
    <ul>
      <li>非遗传承人现场展示传统工艺制作过程</li>
      <li>民间艺术表演，包括木偶戏、采茶戏等</li>
      <li>传统美食制作展示与品尝</li>
      <li>非遗文创产品展销</li>
    </ul>
    <h2>活动流程</h2>
    <p>09:00-10:00 开幕式<br>
       10:00-12:00 非遗项目展示<br>
       14:00-16:00 传统表演艺术展演<br>
       16:00-17:00 互动体验环节</p>
  `,
  coverImage: "/images/events/culture-festival.jpg",
  startTime: "2024-04-15 09:00:00",
  endTime: "2024-04-15 17:00:00",
  registrationEndTime: "2024-04-14 18:00:00",
  location: "贵港市文化中心",
  fee: 0,
  maxParticipants: 500,
  participantsCount: 328,
  isRegistered: false,
  isFollowing: false,
  organizer: {
    name: "贵港市文化旅游局",
    avatar: "/images/avatar/organizer1.jpg",
    description: "致力于推广贵港文化旅游资源，组织各类文化活动",
    eventsCount: 56,
  },
  notices: [
    {
      title: "防疫要求",
      content: "请参与者配合体温检测，保持社交距离，建议佩戴口罩。",
    },
    {
      title: "入场须知",
      content: "请携带身份证件，提前15分钟到达现场签到。",
    },
    {
      title: "拍照说明",
      content: "活动全程可以拍照，但请不要使用闪光灯，以免影响表演者。",
    },
  ],
  participants: [
    {
      id: 1,
      nickname: "文化爱好者",
      avatar: "/images/avatar/user1.jpg",
      registerTime: "2024-03-15 10:00:00",
    },
    {
      id: 2,
      nickname: "摄影达人",
      avatar: "/images/avatar/user2.jpg",
      registerTime: "2024-03-15 11:00:00",
    },
  ],
};

// 报名表单
const showRegistrationForm = ref(false);
const formData = ref({
  name: "",
  phone: "",
  idCard: "",
  remark: "",
});

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
};

// 加载状态
const loading = ref(false);

// 分享相关
const showShareDialog = ref(false);
const sharePlatforms = [
  { name: "weixin", icon: "wechat", label: "微信" },
  { name: "weibo", icon: "weibo", label: "微博" },
  { name: "qq", icon: "qq", label: "QQ" },
];

// 地图弹窗
const showMap = ref(false);

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 是否可以报名
const canRegister = computed(() => {
  if (event.value.isRegistered) return false;
  if (event.value.participantsCount >= event.value.maxParticipants)
    return false;
  if (new Date(event.value.registrationEndTime) < new Date()) return false;
  return true;
});

// 获取报名按钮文本
const getRegisterButtonText = () => {
  if (event.value.isRegistered) return "已报名";
  if (event.value.participantsCount >= event.value.maxParticipants)
    return "名额已满";
  if (new Date(event.value.registrationEndTime) < new Date())
    return "报名已截止";
  return "立即报名";
};

// 获取活动信息
const getEventInfo = async () => {
  loading.value = true;
  try {
    // 调用获取活动信息API
    const response = await service.get(`/public/events/${route.params.id}`);
    console.log("后端返回的活动详情数据:", response);
    
    // 标准响应格式：{code: 200, message: '操作成功', data: {...}}
    const eventData = response && response.data ? response.data : null;
    
    if (eventData) {
      // 如果后端返回了数据，使用后端数据
      const processedEvent = {
        ...eventData,
        // 优先使用image字段，与后端保持一致
        coverImage: eventData.image || eventData.coverImage || "/images/events/default.jpg",
        // 确保已关注状态存在（前端模拟）
        isFollowing: false,
        // 确保组织者信息存在
        organizer: eventData.organizer || {
          name: "贵港文化旅游局",
          avatar: "/images/avatar/organizer1.jpg",
          description: "致力于推广贵港文化旅游资源",
          eventsCount: 0
        },
        // 确保通知和参与者数组存在
        notices: eventData.notices || [],
        participants: eventData.participants || []
      };
      
      // 尝试从localStorage获取关注状态
      const followingEvents = JSON.parse(localStorage.getItem('followingEvents') || '[]');
      processedEvent.isFollowing = followingEvents.includes(Number(route.params.id));
      
      Object.assign(event.value, processedEvent);
      console.log("处理后的活动详情:", event.value);
    } else {
      console.log("后端返回的数据无效，使用测试数据");
      // 如果后端没有返回有效数据，使用测试数据
      Object.assign(event.value, mockEventData);
    }
  } catch (error) {
    console.error("获取活动信息失败:", error);
    // 使用测试数据作为备选
    Object.assign(event.value, mockEventData);
    ElMessage.warning("获取活动详情失败，显示测试数据");
  } finally {
    loading.value = false;
  }
};

// 处理报名
const handleRegister = () => {
  if (!canRegister.value) return;
  // 检查是否登录
  const token = localStorage.getItem("token");
  if (!token) {
    ElMessageBox.confirm("您需要登录才能报名参加活动", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "info"
    }).then(() => {
      router.push({
        path: "/login",
        query: { redirect: router.currentRoute.value.fullPath }
      });
    }).catch(() => {});
    return;
  }
  
  showRegistrationForm.value = true;
};

// 提交报名
const submitRegistration = async () => {
  try {
    loading.value = true;
    // 尝试调用报名API
    try {
      const response = await service.post(`/events/${event.value.id}/register`, formData.value);
      if (response) {
        event.value.isRegistered = true;
        event.value.participantsCount += 1;
        showRegistrationForm.value = false;
        ElMessage.success("报名成功");
      }
    } catch (error) {
      console.error("API报名失败，使用模拟报名:", error);
      // 模拟报名成功
      await new Promise((resolve) => setTimeout(resolve, 1000));
      event.value.isRegistered = true;
      event.value.participantsCount += 1;
      showRegistrationForm.value = false;
      ElMessage.success("报名成功");
    }
  } catch (error) {
    console.error("报名失败:", error);
    ElMessage.error("报名失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 生成分享链接
const generateShareUrl = () => {
  return `${window.location.origin}/community/event/${event.value.id}`;
};

// 处理关注
const handleFollow = async () => {
  // 检查是否登录
  const token = localStorage.getItem("token");
  if (!token) {
    ElMessageBox.confirm("您需要登录才能关注活动", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "info"
    }).then(() => {
      router.push({
        path: "/login",
        query: { redirect: router.currentRoute.value.fullPath }
      });
    }).catch(() => {});
    return;
  }
  
  try {
    loading.value = true;
    
    // 前端模拟关注功能
    const eventId = Number(route.params.id);
    const followingEvents = JSON.parse(localStorage.getItem('followingEvents') || '[]');
    
    if (event.value.isFollowing) {
      // 取消关注
      const index = followingEvents.indexOf(eventId);
      if (index !== -1) {
        followingEvents.splice(index, 1);
      }
    } else {
      // 添加关注
      if (!followingEvents.includes(eventId)) {
        followingEvents.push(eventId);
      }
    }
    
    // 保存到localStorage
    localStorage.setItem('followingEvents', JSON.stringify(followingEvents));
    
    // 更新状态
    event.value.isFollowing = !event.value.isFollowing;
    
    // 提示用户
    ElMessage.success(event.value.isFollowing ? "关注成功" : "已取消关注");
    
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 添加到日历
const handleAddCalendar = () => {
  const startDate = new Date(event.value.startTime);
  const endDate = new Date(event.value.endTime);
  
  // 格式化为iCalendar所需的日期格式
  const formatToICalDate = (date) => {
    return date.toISOString().replace(/-|:|\.\d+/g, '');
  };
  
  const startDateFormatted = formatToICalDate(startDate);
  const endDateFormatted = formatToICalDate(endDate);
  
  // 创建iCalendar文件内容
  const icsContent = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'BEGIN:VEVENT',
    `SUMMARY:${event.value.title}`,
    `DTSTART:${startDateFormatted}`,
    `DTEND:${endDateFormatted}`,
    `LOCATION:${event.value.location}`,
    `DESCRIPTION:${event.value.title} - ${event.value.location}`,
    'END:VEVENT',
    'END:VCALENDAR'
  ].join('\n');
  
  // 创建Blob对象
  const blob = new Blob([icsContent], { type: 'text/calendar;charset=utf-8' });
  
  // 创建下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${event.value.title}.ics`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  ElMessage.success('已添加到日历');
};

// 联系主办方
const handleContactOrganizer = () => {
  ElMessageBox.alert(
    `<div>
      <p><strong>主办方</strong>: ${event.value.organizer.name}</p>
      <p><strong>联系电话</strong>: 0775-12345678</p>
      <p><strong>电子邮箱</strong>: contact@guigangculture.org</p>
    </div>`,
    '联系主办方',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  );
};

// 初始化
onMounted(() => {
  getEventInfo();
});
</script>

<style lang="scss">
.event-page {
  .info-card {
    .info-item {
      @apply border-l-2 border-primary-500 pl-4;
    }
  }

  .content-card {
    .prose {
      h2 {
        @apply text-2xl font-bold mb-4 mt-8;
      }

      p {
        @apply mb-4 leading-relaxed;
      }

      ul {
        @apply list-disc pl-6 mb-4;

        li {
          @apply mb-2;
        }
      }
    }
  }

  .organizer-card,
  .participants-card {
    @apply transition-all duration-300;

    &:hover {
      @apply shadow-md;
    }
  }
}
</style>
